Skip to main content

Same Tree

Question

Given two binary trees, determine if they are the same tree, meaning they are structurally identical and contain the same values.

Example 1
Input: 
Tree 1:
1
/ \
2 3

Tree 2:
1
/ \
2 3

Output: True

Solution

all//Same Tree.py


# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p is None and q is None:
return True
if p is None or q is None:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)